package com.devframe.component.ftlprocess.xml.parse;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.log4j.Logger;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.devframe.component.ftlprocess.meta.Model;

/**
 * 
 * @author 詹保山(softzbs@126.com)
 * Mar 15, 2012<br/>
 * @描述：使用SAX解析XML
 *
 */
public class ModelXmlParser {
	
	private static Logger logger = Logger.getLogger(ModelXmlParser.class);
	
	/**
	 * model XML的前缀
	 */
	private static String ModelXmlStartTag="<model>";
	/**
	 * Model XML的后缀
	 */
	private static String ModelXmlEndTag="</model>";
	

	private  SAXParser getSAXParser(){
			try {
				return SAXParserFactory.newInstance().newSAXParser();
			} catch (ParserConfigurationException e) {
				logger.error(e);
				e.printStackTrace();
			} catch (SAXException e) {
				logger.error(e);
				e.printStackTrace();
			}
			return null;
		}

	
	
	
	/**
	 * 解析model的XML
	 * @param xml
	 * @return
	 * @author:詹保山
	 */
	public Model parserModelXml(String xml){
		logger.info("解析XML");
		StringBuffer sb=new StringBuffer(32);
		//构造完整的model XML格式串
		sb.append(ModelXmlParser.ModelXmlStartTag).append(xml).append(ModelXmlParser.ModelXmlEndTag);
		StringReader stringReader=new StringReader(sb.toString());
		InputSource inputSource=new InputSource(stringReader);
		SAXParser saxParser;
		try {
			Model model=new Model();
			//解析
			saxParser=this.getSAXParser();
			saxParser.parse(inputSource,model);
			return model;
		} catch (IOException e) {
			logger.info("解析XML出错;XML="+sb);
		} catch (SAXException e) {
			logger.info("解析XML出错;XML="+sb);
			e.printStackTrace();
		}finally{
			//清空数据
			sb=null;
			saxParser=null;
			stringReader=null;
			inputSource=null;
		}
		return null;
	}

	
}
